package protocol;

import com.google.gson.*;
import play.Play;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;

/**
 * 请求及响应json格式处理类
 * 
 * @author yangzhi@djcars.cn
 * @createDate 2012-8-17
 * 
 */
public class JsonHandler {

    /**
     * 请求的JSON格式对象
     */
    private static Gson requestGson;

    /**
     * 响应的JSON格式对象
     */
    private static Gson responseGson;

    static {
        GsonBuilder builder = new GsonBuilder();
        builder.registerTypeAdapter(JsonRequest.class, new JsonDeserializer<Object>() {

            @Override
            public Object deserialize(JsonElement jsonElement, Type type,
                    JsonDeserializationContext jsonDeserializationContext)
                    throws JsonParseException {
                JsonObject jsonObject = jsonElement.getAsJsonObject();
                JsonRequest json = new JsonRequest();
                JsonElement tempElement = jsonObject.get("id");
                if (tempElement != null && !tempElement.isJsonNull()) {
                    json.id = tempElement.getAsString();
                }

                tempElement = jsonObject.get("service");
                if (tempElement != null && !tempElement.isJsonNull()) {
                    json.service = tempElement.getAsString();
                }

                tempElement = jsonObject.get("encrypt");
                if (tempElement != null && !tempElement.isJsonNull()) {
                    json.encrypt = tempElement.getAsString();
                }
                tempElement = jsonObject.get("sign");
                if (tempElement != null && !tempElement.isJsonNull()) {
                    json.sign = tempElement.getAsString();
                }

                tempElement = jsonObject.get("client");
                if (tempElement != null && !tempElement.isJsonNull()) {
                    JsonObject clientObj = tempElement.getAsJsonObject();
                    JsonRequest.Client client = new JsonRequest.Client();

                    tempElement = clientObj.get("caller");
                    if (tempElement != null && !tempElement.isJsonNull()) {
                        client.caller = clientObj.get("caller").getAsString();
                    }

                    tempElement = clientObj.get("ex");
                    if (tempElement != null && !tempElement.isJsonNull()) {
                        client.ex = tempElement.getAsString();
                    }
                    json.client = client;
                }

                tempElement = jsonObject.get("data");
                if (tempElement != null && !tempElement.isJsonNull()) {
                    json.data = tempElement.getAsJsonObject();
                }
                return json;
            }
        });
        requestGson = builder.create();

        if (Play.configuration.getProperty("http.json_readable_response", "false").equals("true")) {
            responseGson = new GsonBuilder().setPrettyPrinting().serializeNulls().create();
        } else {
            responseGson = new Gson();
        }
    }

    /**
     * 解析请求内容，得到JsonRequest对象
     * 
     * @param body
     * @return
     * @throws com.google.gson.JsonSyntaxException
     * @throws com.google.gson.JsonIOException
     * @throws java.io.UnsupportedEncodingException
     */
    public static JsonRequest parseRequestBody(InputStream body) throws JsonSyntaxException,
            JsonIOException, UnsupportedEncodingException {
        InputStreamReader inputStream = new InputStreamReader(body, "utf-8");
        return requestGson.fromJson(inputStream, JsonRequest.class);
    }

    /**
     * 将响应对象Json序列化
     * 
     * @param response
     * @return
     */
    public static String toResponseString(JsonResponse response) {
        return responseGson.toJson(response);
    }
}
